﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using BusinessLayer.BLServerReference;
using BusinessLayer;
using System.Configuration;
using System.Web.Script.Services;

namespace WebFrontEnd.Services
{
    /// <summary>
    /// Summary description for UsersService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class UsersService : System.Web.Services.WebService
    {

        #region Private Members
        private IBL _bl;
        private User _currentUser;
        #endregion

        #region Private Properties
        private IBL BL
        {
            //Lazy Loading
            get
            {
                if (_bl == null)
                {
                    _bl = BusinessLayerFactory.GetCurrentBusinessLayer(ConfigurationManager.AppSettings.Get("DomainName"));
                }
                return _bl;
            }
        }

        private User CurrentUser
        {
            //Lazy Loading
            get
            {
                if (_currentUser == null)
                {
                    _currentUser = GetCurrentUser();
                }
                return _currentUser;
            }
        }
        #endregion

        #region Private Methods
        protected User GetCurrentUser()
        {
            return BL.GetUserByEmail(User.Identity.Name);
        }
        #endregion

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public object ListUsers(string jtStartIndex, string jtPageSize, string jtSorting)
        {
            if (CurrentUser.Role != Role.Admin)
            {
                return new { Result="ERROR", Message="You do not have permission to view this."};
            }
            var users = BL.GetAllUsers().ToList();
            List<object> users2 = new List<object>();
            foreach (var user in users)
            {
                users2.Add(new
                {
                    ID = user.ID,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Email = user.Email,
                    Role = user.Role
                });
            }
            return new { Result = "OK", Records = users2.ToArray(), TotalRecordCount = users.Count };
        }
    }
}
